package me.leon.ade

import java.lang.ref.Reference
import java.lang.ref.ReferenceQueue
import java.lang.ref.WeakReference
import java.util.*
import kotlin.concurrent.thread
import me.leon.ext.java.Base64Utils
import org.junit.Assert.assertEquals
import org.junit.Test

/**
 * Example local unit test, which will execute on the development machine (host).
 *
 * See [testing documentation](http://d.android.com/tools/testing).
 */
class ExampleUnitTest {
    @Test
    fun addition_isCorrect() {
        assertEquals(4, 2 + 2)
    }

    val finalWeakLazyDelegate = weakLazy { listOf(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) }

    val finalValue by finalWeakLazyDelegate

    private val rq: ReferenceQueue<Any> = ReferenceQueue<Any>()

    fun checkQueue() {
        var ref: Reference<out Any?>? = null
        while (true) {
            rq.poll().also { ref = it }
            if ((ref != null).also { if (it) println("In queue judge: $ref") }) {
                System.out.println("In queue: " + (ref as? Any?))
            }
        }
    }

    @Test
    fun gcTest() {

        thread { checkQueue() }
        val wr = WeakReference(ByteArray(1024 * 1024), rq)
        println("$finalValue hasValue: " + finalWeakLazyDelegate.hasValue)
        println(finalValue)
        println("$finalValue hasValue: " + finalWeakLazyDelegate.hasValue)

        System.gc() // or  finalWeakLazyDelegate.clearWeakValue()
        println(" hasValue: " + finalWeakLazyDelegate.hasValue)
        println(wr.get())
        System.gc()

        while (true) {
            // dead loop
        }
    }

    @Test
    fun content_md5() {
        val md5 = "OGFkZDUwNGVhNGY3N2MxMDIwZmQ4NTBmY2IyTY=="
        println(String(Base64Utils.decode(md5)))
        println(Base64Utils.decode(md5).contentToString())
    }
}
